/*
    BibleNotebook - A bible reader software
    Copyright (C) 2014  Williams Fernando Lopez

    This program is free software: you can redistribute it and/or modify
    it under the terms of the GNU General Public License as published by
    the Free Software Foundation, either version 3 of the License, or
    (at your option) any later version.

    This program is distributed in the hope that it will be useful,
    but WITHOUT ANY WARRANTY; without even the implied warranty of
    MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE.  See the
    GNU General Public License for more details.

    You should have received a copy of the GNU General Public License
 */

package com.simplebible.dictionary;

import com.simplebible.dictionary.objects.SimpleIndex;
import com.simplebible.dictionary.objects.NodeIndex;
import java.io.File;
import java.io.IOException;
import java.util.ArrayList;
import java.util.List;
import wl.util.TextResourcesUtil;
import wl.util.Utils;
import com.simplebible.objects.Preferences;

/**
 *
 * @author Williams Lopez
 */
public class DictionaryUtils {

    private static String pathDictionaries = "dicts";
    private static String pathSwordDictionaries = "dicts"+File.separator+"mods.d";
    private static String customDictName = "mydict";
    private static IDictionary customDict;
    private static List<IDictionary> dictionaries = null;


    public static void cleanDictionaryCache(){
        if(dictionaries!=null){
            for(IDictionary df : dictionaries){
                try {
                    df.close();
                } catch (Exception e) {
                }
            }
            dictionaries.clear();
            dictionaries = null;
        }
        
    }


    public static IDictionary getDictionaryById(String id) throws IOException{
        List<IDictionary> dicts = getDictionaries();
        for(IDictionary d:dicts){
            if(d.getDictionaryId()!=null && d.getDictionaryId().equals(id)){
                return d;
            }
        }
        return null;
    }


    public static List<IDictionary> getDictionaries() throws IOException {
        if(dictionaries !=null){
            return dictionaries;
        }

        dictionaries = new ArrayList<IDictionary>();

        File dir = new File(pathDictionaries);

        if(!dir.exists()){
            dir.mkdir();
        }

        for (File f : dir.listFiles()) {
            if (f.getName().endsWith(".files") || f.isDirectory()) {
                continue;
            }
            try {
                DictionaryFile df = new DictionaryFile(f.getAbsolutePath());
                if (df.getDictionaryName() == null) { continue; }
                dictionaries.add(df);
            } catch (Exception e) {
                Utils.printToLog("Error al leer diccionario:" + f.getAbsolutePath(), e, Preferences.LOG_LEVEL_ERROR);
            }
        }
   
        File swordDir = new File(pathSwordDictionaries);

        if(!swordDir.exists()){
            swordDir.mkdir();
        }

        if (swordDir.exists()) {
            File[] content = swordDir.listFiles();
            if (content != null && content.length > 0) {
                for (File f : content) {
                    if (!f.isDirectory()) {
                        try {
                            SwordDictionary swdict = new SwordDictionary(f);
                            dictionaries.add(swdict);
                        } catch (Exception e) {
                            Utils.printToLog("Error al leer diccionario:" + f.getAbsolutePath(), e, Preferences.LOG_LEVEL_ERROR);
                        }
                    }
                }
            }
        }
        return dictionaries;
    }

    public static boolean removeDictionary(IDictionary dict) throws Exception {
        dict.close();
        cleanDictionaryCache();
        Thread.currentThread().sleep(500);
        return dict.removeOfSystem();
    }

    public static IDictionary getCustomDictionary() throws IOException{
        List<IDictionary> dicts = getDictionaries();
        for(IDictionary df: dicts){
                if(df.getDictionaryName().equals(customDictName)){
                    customDict = df;
                }
            }
            if(customDict == null){
                customDict = new DictionaryFile(pathDictionaries+File.separator+customDictName);
                customDict.setDictionaryInfo("Mi diccionario", "--", "--", "--","es");
                dictionaries = null;
                dictionaries = getDictionaries();
            }
        return customDict;
    }

    public static boolean isIgnoredWord(String word){
        String strIgnored=TextResourcesUtil.getText("ignored_dictionary_words");
        String[] words = strIgnored.split(",");
        for(String s: words){
            if(s.trim().equalsIgnoreCase(word.trim())){
                return true;
            }
        }
        return false;
    }

    public static String addHrefToWords(String text, String a_href) {
        StringBuilder buff = new StringBuilder();
        StringBuilder buffWord = new StringBuilder();
        for (int i = 0; i < text.length(); i++) {
            char c = text.charAt(i);
            if (Character.isLetterOrDigit(c)) {
                buffWord.append(c);
            } else {
                if (buffWord.length() > 0) {
                    String word = buffWord.toString();
                    Integer isNum = null;
                    try {
                        isNum = Integer.parseInt(word);
                    } catch (Exception e) { }
                    if (!isIgnoredWord(word) && isNum == null) {
                        buff.append(a_href.replace("{w}", buffWord.toString()));
                        buff.append(buffWord);
                        buff.append("</a>");
                    }else{
                        buff.append(buffWord);
                    }
                    buffWord.delete(0, buffWord.length());
                }
                buff.append(c);
            }
        }


        if (buffWord.length() > 0) {
            String word = buffWord.toString();
            Integer isNum = null;
            try {
                isNum = Integer.parseInt(word);
            } catch (Exception e) {
            }
            if (!isIgnoredWord(word) && isNum == null) {
                buff.append(a_href.replace("{w}", buffWord.toString()));
                buff.append(buffWord);
                buff.append("</a>");
            } else {
                buff.append(buffWord);
            }
            buffWord.delete(0, buffWord.length());
        }

        return buff.toString();
    }

    public static SimpleIndex createSimpleIndex(List<String> list){
        SimpleIndex simpleIndex = new SimpleIndex();
        simpleIndex.setWords(list);
        recursiveCreateIndex(null,simpleIndex, 1, 2);
        return simpleIndex;
    }

    public static void recursiveCreateIndex(NodeIndex parent,NodeIndex index,int count, int maxcount){

        if(count >= maxcount) return;

        index.setParent(parent);
        index.setChildren(new ArrayList<NodeIndex>());
        for(String s:index.getWords()){
            s = s.trim();
            if(s.trim().length()<1) continue;
            String key = Utils.substring(s,0, count);
            NodeIndex node = new NodeIndex();
            node.setValue(key);
            int i = index.getChildren().indexOf(node);
            if(i < 0){
                index.getChildren().add(node);
            }else{
                node = index.getChildren().get(i);
            }
            if(node.getWords()==null){
                node.setWords(new ArrayList<String>());
            }
            node.getWords().add(s);
        }

        index.setWords(null);


        if(index.getChildren()!=null && !index.getChildren().isEmpty()){
            
            for(NodeIndex ni:index.getChildren()){
                recursiveCreateIndex(index,ni, count+1, maxcount);
            }
        }


    }



}
